<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>
<script>

    (function(){
        function Observer(){
            //用来保存传入的消息类型
            this.obj = {};
            //订阅
            this.on = function(type,handler){
                this.obj[type] = (this.obj[type] ? this.obj[type] : []);
                this.obj[type].push(handler);
            }
            //发布
            this.emit = function(type,msg){
                if(this.obj[type]){
                    this.obj[type].forEach((item) => {
                        item(msg);
                    });
                }
            }
        }
        //将闭包函数暴露到全局
        window.Observer = Observer;
    })()

    //实例化对象
    let os = new Observer();

    //订阅
    os.on('唐僧',function(msg){
        console.log('孙悟空 收到了来自唐僧的消息: ' + msg);
    })
    os.on('唐僧',function(msg){
        console.log('猪八戒 收到了来自唐僧的消息: ' + msg);
    })
    os.on('唐僧',function(msg){
        console.log('沙和尚 收到了来自唐僧的消息: ' + msg);
    })

    //发布
    os.emit('唐僧','明天出发取经');

</script>